package com.nanhai.buddhist.college.module.collegebase.controller.admin.studentroll;

import com.nanhai.buddhist.college.framework.common.pojo.CommonResult;
import com.nanhai.buddhist.college.framework.common.pojo.PageResult;
import com.nanhai.buddhist.college.framework.common.util.collection.CollectionUtils;
import com.nanhai.buddhist.college.framework.excel.core.util.ExcelUtils;
import com.nanhai.buddhist.college.framework.operatelog.core.annotations.OperateLog;
import com.nanhai.buddhist.college.module.collegebase.controller.admin.studentroll.vo.*;
import com.nanhai.buddhist.college.module.collegebase.convert.studentroll.StudentRollConvert;
import com.nanhai.buddhist.college.module.collegebase.dal.dataobject.studentroll.StudentRollDO;
import com.nanhai.buddhist.college.module.collegebase.service.studentroll.StudentRollService;
import com.nanhai.buddhist.college.module.system.api.user.AdminUserApi;
import com.nanhai.buddhist.college.module.system.api.user.dto.AdminUserRespDTO;
import com.tencentcloudapi.ame.v20190916.models.Item;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

import static com.nanhai.buddhist.college.framework.common.pojo.CommonResult.success;
import static com.nanhai.buddhist.college.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Api(tags = "管理后台 - 学员信息")
@RestController
@RequestMapping("/collegebase/student-roll")
@Validated
public class StudentRollController {

    @Resource
    private StudentRollService studentRollService;

    @PostMapping("/create")
    @ApiOperation("创建学员信息")
    @PreAuthorize("@ss.hasPermission('collegebase:student-roll:create')")
    public CommonResult<String> createStudentRoll(@Valid @RequestBody StudentRollCreateReqVO createReqVO) {
        return success(studentRollService.createStudentRoll(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新学员信息")
    @PreAuthorize("@ss.hasPermission('collegebase:student-roll:update')")
    public CommonResult<Boolean> updateStudentRoll(@Valid @RequestBody StudentRollUpdateReqVO updateReqVO) {
        studentRollService.updateStudentRoll(updateReqVO);
        return success(true);
    }

    @PutMapping("/check")
    @ApiOperation("审核学员信息")
    @PreAuthorize("@ss.hasPermission('collegebase:student-roll:update')")
    public CommonResult<Boolean> checkStudentRoll(@Valid @RequestBody StudentRollCheckReqVo req) {
        studentRollService.checkStudentRoll(req);
        return success(true);
    }


    @DeleteMapping("/delete")
    @ApiOperation("删除学员信息")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('collegebase:student-roll:delete')")
    public CommonResult<Boolean> deleteStudentRoll(@RequestParam("id") String id) {
        studentRollService.deleteStudentRoll(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得学员信息")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('collegebase:student-roll:query')")
    public CommonResult<StudentRollRespVO> getStudentRoll(@RequestParam("id") String id) {
        StudentRollDO studentRoll = studentRollService.getStudentRoll(id);
        return success(StudentRollConvert.INSTANCE.convert(studentRoll));
    }

    @GetMapping("/list")
    @ApiOperation("获得学员信息列表")
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClass = List.class)
    @PreAuthorize("@ss.hasPermission('collegebase:student-roll:query')")
    public CommonResult<List<StudentRollRespVO>> getStudentRollList(@RequestParam("ids") Collection<String> ids) {
        List<StudentRollDO> list = studentRollService.getStudentRollList(ids);
        return success(StudentRollConvert.INSTANCE.convertList(list));
    }

    @Resource
    private AdminUserApi adminUserApi;

    @GetMapping("/page")
    @ApiOperation("获得学员信息分页")
    @PreAuthorize("@ss.hasPermission('collegebase:student-roll:query')")
    public CommonResult<PageResult<StudentRollRespVO>> getStudentRollPage(@Valid StudentRollPageReqVO pageVO) {
        PageResult<StudentRollDO> pageResult = studentRollService.getStudentRollPage(pageVO);
        Set<String> strings = CollectionUtils.convertSet(pageResult.getList(), StudentRollDO::getCheckUser);
        Map<String, AdminUserRespDTO> longAdminUserRespDTOMap = Collections.EMPTY_MAP;
        if (!strings.isEmpty()) {
            CommonResult<List<AdminUserRespDTO>> users = adminUserApi.getUsers(strings);
            longAdminUserRespDTOMap = CollectionUtils.convertMap(users.getData(), AdminUserRespDTO::getId);

        }
        PageResult<StudentRollRespVO> studentRollRespVOPageResult = StudentRollConvert.INSTANCE.convertPage(pageResult);
        Map<String, AdminUserRespDTO> finalLongAdminUserRespDTOMap = longAdminUserRespDTOMap;
        studentRollRespVOPageResult.getList().forEach(item -> {
            if (StringUtils.hasText(item.getCheckUser())) {
                item.setCheckUser(Optional.ofNullable(finalLongAdminUserRespDTOMap).map(s -> s.get(item.getCheckUser())).map(AdminUserRespDTO::getNickname).orElse(""));
            }
        });
        return success(studentRollRespVOPageResult);
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出学员信息 Excel")
    @PreAuthorize("@ss.hasPermission('collegebase:student-roll:export')")
    @OperateLog(type = EXPORT)
    public void exportStudentRollExcel(@Valid StudentRollPageReqVO exportReqVO,
                                       HttpServletResponse response) throws IOException {

        exportReqVO.setPageNo(1);
        exportReqVO.setPageSize(999999);
        PageResult<StudentRollDO> pageResult = studentRollService.getStudentRollPage(exportReqVO);
        if (pageResult == null) pageResult = new PageResult<StudentRollDO>();
        // 导出 Excel
        List<StudentRollExcelVO> list = StudentRollConvert.INSTANCE.convertList02(pageResult.getList());

        Set<String> strings = CollectionUtils.convertSet(pageResult.getList(), StudentRollDO::getCheckUser);
        Map<String, AdminUserRespDTO> longAdminUserRespDTOMap = Collections.EMPTY_MAP;
        if (!strings.isEmpty()) {
            CommonResult<List<AdminUserRespDTO>> users = adminUserApi.getUsers(strings);
            longAdminUserRespDTOMap = CollectionUtils.convertMap(users.getData(), AdminUserRespDTO::getId);

        }
        Map<String, AdminUserRespDTO> finalLongAdminUserRespDTOMap = longAdminUserRespDTOMap;
        list.forEach(item -> {
            if (StringUtils.hasText(item.getCheckUser())) {
                item.setCheckUser(Optional.ofNullable(finalLongAdminUserRespDTOMap).map(s -> s.get(item.getCheckUser())).map(AdminUserRespDTO::getNickname).orElse(""));
            }
        });

        ExcelUtils.write(response, "学员信息.xls", "数据", StudentRollExcelVO.class, list);
    }

    @GetMapping("/byFindStr/list")
    @ApiOperation("获得学员信息列表--多添条件模糊查询支持(学号、编号、法名、姓名)")
    @ApiImplicitParam(name = "findStr", value = "查询条件", required = true, example = "1024,2048", dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('collegebase:student-roll:query')")
    public CommonResult<List<StudentRollRespVO>> getStudentRollListByStr(@RequestParam("findStr") String findStr) {
        List<StudentRollDO> list = studentRollService.getStudentRollListByStr(findStr);
        return success(StudentRollConvert.INSTANCE.convertList(list));
    }


}
